#include "common.h"
#include "text.h"
#include "SDL_rotozoom.h"

void init_text(text* t, char* text, int x, int y, int w, int h)
{
	strcpy(t->str, text);
	t->init_str = 1;
	t->max_len = 16;

  t->font = TTF_OpenFont("/usr/share/fonts/arial.ttf", 18);
	t->fg_color.r = 0xFF;
	t->fg_color.g = 0xFF;
	t->fg_color.b = 0xFF;

	SDL_Surface* tmp_surf;
	tmp_surf = TTF_RenderText_Solid(t->font, t->str, t->fg_color);
	t->str_surf = rotozoomSurface(tmp_surf, 90.0, 1.0, 0);

	// flipped for vert
	t->rect.x = x;
	t->rect.y = y; 
	t->rect.h = t->str_surf->h+10; 
	t->rect.w = t->str_surf->w+10;

	// setup text surface
	
}

void free_text(text* s)
{
	SDL_FreeSurface(s->str_surf); 
	TTF_CloseFont(s->font);
}

void input_text(text* t, char c)
{
	if (t->init_str)
	{
		t->str[0] = '\0';
		t->init_str = 0;
	}
	int len = strlen(t->str);
	
	// backspace
	if (c == 0x08)
	{
		if (len > 0)
			t->str[len-1] = '\0';
	}

	// norml ip char
	if (len < (t->max_len-1) && ((c >= 48 && c <= 57) || c == 46))
	{
		t->str[len] = c;
		t->str[len+1] = '\0';
	}

	char tmp[100];
	tmp[0] = '\0';
	strcat(tmp, "IP: ");
	strcat(tmp, t->str);
	SDL_Surface* tmp_surf;
	tmp_surf = TTF_RenderText_Solid(t->font, tmp, t->fg_color);
	SDL_FreeSurface(t->str_surf);
	t->str_surf = rotozoomSurface(tmp_surf, 90.0, 1.0, 0);
	SDL_FreeSurface(tmp_surf);
}

void display_text(SDL_Surface* screen, text* s)
{
	SDL_Rect text_offset;
	text_offset.x = s->rect.x+5;
	text_offset.y = (s->rect.y+s->rect.h-5)-s->str_surf->h;
	//text_offset.y = s->rect.y + (0.5*(s->rect.h-s->str_surf->h));

	SDL_FillRect(screen, &s->rect, SDL_MapRGB(screen->format, 0xFF, 0x00, 0x00));
	SDL_BlitSurface(s->str_surf, NULL, screen, &text_offset);
}
